package com.plat.api.api.action.service;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.plat.api.common.RespCode;
import com.plat.api.dao.api.TokenDao;
import com.plat.api.entity.api.TokenEntity;
import com.plat.api.exception.PlatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/5/9
 * Time: 22:49
 * Description: No Description
 */
@Component
@Slf4j
public class PlatTokenService {

    @Autowired
    private TokenDao tokenDao;

    public String createToken(Integer user_id) {
        TokenEntity tokenEntity = tokenDao.createLambdaQuery().andEq("user_id",user_id).single();
        String token = RandomUtil.randomString(25);
        if (tokenEntity == null) {
            tokenEntity = new TokenEntity();
            tokenEntity.setUserId(user_id);
            tokenEntity.setToken(token);
            tokenDao.insert(tokenEntity);
        }
        tokenEntity = tokenDao.getSQLManager().lambdaQuery(TokenEntity.class).andEq("user_id",user_id).single();
        tokenEntity.setUserId(user_id);
        tokenEntity.setToken(token);
        tokenEntity.setCreateTime(new Date());
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 7);
        tokenEntity.setExpireTime(c.getTime());
        c.add(Calendar.DATE, 14);
        tokenEntity.setRefreshTime(c.getTime());
        try {
            tokenDao.updateById(tokenEntity);
        } catch (PlatException platException) {
            throw new PlatException(RespCode.WX_AUTH_ERROR.getCode(), "生成token数据处理失败");
        }
        log.info("认证开始生成token" + JSONObject.toJSONString(tokenEntity));
        return token;
    }
}
